# ui.py

import logging
from pathlib import Path
from traceback import format_exc

from PyQt6.QtWidgets import (
    QWidget, QVBoxLayout, QLabel, QPushButton,
    QFileDialog, QMessageBox
)
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QDropEvent, QDragEnterEvent

from core import run_demucs
from config import Config


class DemucsGUI(QWidget):
    def __init__(self, config: Config):
        super().__init__()
        self.setWindowTitle("Demucs GUI")
        self.setAcceptDrops(True)

        self.config = config
        self.selected_file = config.last_file
        self.output_format = config.output_format or "wav"

        self.init_ui()

        if self.selected_file:
            labelText = f"Selected: {self.selected_file}"
            labelText += f" (format: {self.output_format})"
            self.file_label.setText(labelText)

    def init_ui(self):
        layout = QVBoxLayout()

        self.file_label = QLabel("Drop an audio file here or click to select")
        self.file_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(self.file_label)

        browse_button = QPushButton("Browse")
        browse_button.clicked.connect(self.browse_file)
        layout.addWidget(browse_button)

        run_button = QPushButton("Run Demucs")
        run_button.clicked.connect(self.run_separation)
        layout.addWidget(run_button)

        self.setLayout(layout)

    def browse_file(self):
        file_path, _ = QFileDialog.getOpenFileName(
            self, "Select Audio File", "", "Audio Files (*.mp3 *.wav *.flac *.ogg)")
        if file_path:
            self.selected_file = file_path
            self.file_label.setText(f"Selected: {file_path}")

    def dragEnterEvent(self, event: QDragEnterEvent):
        if event.mimeData().hasUrls():
            event.acceptProposedAction()

    def dropEvent(self, event: QDropEvent):
        urls = event.mimeData().urls()
        if urls:
            file_path = urls[0].toLocalFile()
            self.selected_file = file_path
            self.file_label.setText(f"Dropped: {file_path}")

    def run_separation(self):
        if not self.selected_file:
            QMessageBox.warning(
                self, "No file", "Please select or drop an audio file.")
            return

        try:
            logging.info(f"Running Demucs on: {self.selected_file}")
            out_dir = run_demucs(self.selected_file, self.output_format)
            QMessageBox.information(
                self, "Done", f"Separated files saved to:\n{out_dir}")

            # ✅ 更新配置并保存
            self.config.last_file = self.selected_file
            self.config.output_format = self.output_format
            self.config.save()

        except Exception as e:
            logging.error(f"Error: {e}\n{format_exc()}")
            QMessageBox.critical(self, "Error", f"Failed to run Demucs:\n{e}")
